import java.util.Random;

public class Solution2 {
    public int findKthLargest(int[] nums, int k) {
        //使用快速选择算法解决问题 - 数组分三块 随机找key值
        int l = 0;
        int r = nums.length - 1;
        return quickSort(nums, l, r, k);
    }
    private int quickSort(int[] nums, int l, int r, int k){
        if(l >= r) return nums[l];
        int left = l - 1;
        int right = r + 1;
        int cur = l;
        int key = nums[new Random().nextInt(r - l + 1) + l];
        while(cur < right){
            if(nums[cur] < key){
                swap(nums, ++left, cur++);
            }else if(nums[cur] == key){
                cur++;
            }else{
                swap(nums, --right, cur);
            }
        }
        //分情况讨论第k大的元素落在哪个区域
        if(k <= (r - right + 1)){
            return quickSort(nums, right, r, k);
        }else if(k <= r - left){
            return key;
        }else{
            return quickSort(nums, l, left, k - (r - left));
        }
    }
    private void swap(int[] nums, int i, int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
